﻿using KZ.Express.ENT;
using KZ.Express.Presenter;
using KZ.Express.Resource;
using KZ.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KZ.Express.Order.Order
{
    public partial class OrderListView : FormBase, IOrderListView
    {
        #region Private Variables

        bool _isVisible, _isViewOriginal;
        int _supplierID, _carrierID;
        Dictionary<string, DataTable> _tables;
        Dictionary<string, DataGridView> _dataGrids;
        Dictionary<string, BindingSource> _bindingSource;
        Dictionary<string, bool> _isLoad;
        Dictionary<string, string> _orderBy;
        Dictionary<string, string> _orderDirection;
        Dictionary<string, Dictionary<int, string>> _errors;
        new OrderListPresenter _presenter;

        #endregion

        #region Private Methods

        private void OrderView_Load(object sender, EventArgs e)
        {
            _tables = new Dictionary<string, DataTable>();
            _dataGrids = new Dictionary<string, DataGridView>();
            _bindingSource = new Dictionary<string, BindingSource>();
            _isLoad = new Dictionary<string, bool>();
            _orderBy = new Dictionary<string, string>();
            _orderDirection = new Dictionary<string, string>();
            dtpFrom.Value = DateTime.Today.GetFirstDayOfMonth();
            dtpTo.Value = DateTime.Today.GetLastDayOfMonth();

            LoadCountry();
            LoadSupplierCarrier();
        }

        private void OrderListView_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible && !_isVisible)
                tbcOrder_SelectedIndexChanged(tbcOrder, null);
            _isVisible = this.Visible;
        }

        private void tbcOrder_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (tbcOrder.SelectedTab == null) return;
                if (!_isLoad.ContainsKey(tbcOrder.SelectedTab.Name)) return;

                int numberDigit = Utility.Info.NumberFormat.NumberDecimalDigits;
                int currencyDigit = Utility.Info.NumberFormat.CurrencyDecimalDigits;
                Utility.Info.NumberFormat.NumberDecimalDigits = 1;

                try
                {
                    if (!_isLoad[tbcOrder.SelectedTab.Name])
                    {
                        SetID();
                        _presenter.LoadDataTable();
                    }

                    DataTable dt = _tables[tbcOrder.SelectedTab.Name];
                    txtTotalBill.Text = dt.Rows.Count.ToString();
                    int totalDOX = 0, totalWPX = 0;
                    decimal totalWeight = 0, totalStandardPrice = 0, totalListPrice = 0, totalCost = 0, 
                        totalVNDStandardPrice = 0, totalVNDListPrice = 0, totalDifference = 0;
                    foreach (DataRow row in dt.Rows)
                    {
                        if (Utility.StringParse(row["Type"]) == "DOX")
                            totalDOX++;
                        else
                            totalWPX++;

                        totalWeight += Utility.DecimalParse(row["Weight"]);
                        totalStandardPrice += Utility.DecimalParse(row["StandardPrice"]);
                        totalListPrice += Utility.DecimalParse(row["ListPrice"]);
                        totalCost += Utility.DecimalParse(row["Cost"]);
                        totalVNDStandardPrice += Utility.DecimalParse(row["VNDStandardPrice"]);
                        totalVNDListPrice += Utility.DecimalParse(row["VNDListPrice"]);
                        totalDifference += Utility.DecimalParse(row["Difference"]);
                    }

                    txtTotalDOX.Text = totalDOX.ToString();
                    txtTotalWPX.Text = totalWPX.ToString();
                    txtTotalWeight.Text = Utility.NumberParse(totalWeight, Utility.Info);
                    txtTotalStandardPrice.Text = Utility.CurrencyParse(totalStandardPrice, Utility.Info);
                    txtTotalListPrice.Text = Utility.CurrencyParse(totalListPrice, Utility.Info);

                    Utility.Info.NumberFormat.CurrencyDecimalDigits = 0;
                    txtTotalVNDStandardPrice.Text = Utility.CurrencyParse(totalVNDStandardPrice, Utility.Info);
                    txtTotalVNDListPrice.Text = Utility.CurrencyParse(totalVNDListPrice, Utility.Info);
                    txtDifference.Text = Utility.CurrencyParse(totalDifference, Utility.Info);
                    txtTotalCost.Text = Utility.CurrencyParse(totalCost, Utility.Info);
                }
                catch (BusinessLogicException ex)
                {
                    SetMessage(ex.Message, false);
                }
                finally
                {
                    Utility.Info.NumberFormat.NumberDecimalDigits = numberDigit;
                    Utility.Info.NumberFormat.CurrencyDecimalDigits = currencyDigit;
                }
            }
            catch
            {

            }
        }

        private void txtOrderNumber_TextChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void txtCustomer_TextChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void txtFromWeight_TextChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void txtToWeight_TextChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void cmbType_SelectedValueChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void cmbCountryID_SelectedValueChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void txtFromWeight_Leave(object sender, EventArgs e)
        {
            int numberDigit = Utility.Info.NumberFormat.NumberDecimalDigits;
            Utility.Info.NumberFormat.NumberDecimalDigits = 1;
            try
            {
                decimal? value = Utility.DecimalNParse(txtFromWeight.Text);
                txtFromWeight.Text = Utility.NumberParse(value, Utility.Info);
            }
            finally
            {
                Utility.Info.NumberFormat.NumberDecimalDigits = numberDigit;
            }
        }

        private void txtToWeight_Leave(object sender, EventArgs e)
        {
            int numberDigit = Utility.Info.NumberFormat.NumberDecimalDigits;
            Utility.Info.NumberFormat.NumberDecimalDigits = 1;
            try
            {
                decimal? value = Utility.DecimalNParse(txtToWeight.Text);
                txtToWeight.Text = Utility.NumberParse(value, Utility.Info);
            }
            finally
            {
                Utility.Info.NumberFormat.NumberDecimalDigits = numberDigit;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            foreach (KeyValuePair<string, DataGridView> item in _dataGrids)
                _isLoad[item.Key] = false;

            tbcOrder_SelectedIndexChanged(tbcOrder, null);
        }

        protected override void btnViewAll_Click(object sender, EventArgs e)
        {
            try
            {
                txtOrderNumber.TextChanged -= txtOrderNumber_TextChanged;
                txtCustomer.TextChanged -= txtCustomer_TextChanged;
                txtFromWeight.TextChanged -= txtFromWeight_TextChanged;
                txtToWeight.TextChanged -= txtToWeight_TextChanged;
                cmbType.SelectedIndexChanged -= cmbType_SelectedValueChanged;
                cmbCountryID.SelectedIndexChanged -= cmbCountryID_SelectedValueChanged;

                foreach (KeyValuePair<string, DataGridView> item in _dataGrids)
                    _isLoad[item.Key] = false;

                base.btnViewAll_Click(sender, e);
            }
            finally
            {
                txtOrderNumber.TextChanged += txtOrderNumber_TextChanged;
                txtCustomer.TextChanged += txtCustomer_TextChanged;
                txtFromWeight.TextChanged += txtFromWeight_TextChanged;
                txtToWeight.TextChanged += txtToWeight_TextChanged;
                cmbType.SelectedIndexChanged += cmbType_SelectedValueChanged;
                cmbCountryID.SelectedIndexChanged += cmbCountryID_SelectedValueChanged;
            }
        }

        private void btnImportExcel_Click(object sender, EventArgs e)
        {
            Import();
        }

        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            Export();
        }

        private void btnCustomerExport_Click(object sender, EventArgs e)
        {
            ExportToCustomer();
        }

        private void btnSurcharge_Click(object sender, EventArgs e)
        {
            Surcharge();
        }

        private void _lbl_Click(object sender, EventArgs e)
        {
            if (_errors != null && _errors.Count > 0)
            {
                ErrorView view = new ErrorView();
                view.Errors = _errors;
                view.Show();
            }
        }

        protected override void LoadData()
        {
            try
            {
                _presenter.LoadDataTable();
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        private void LoadCountry()
        {
            try
            {
                cmbCountryID.SelectedValueChanged -= cmbCountryID_SelectedValueChanged;
                Global.LoadComboBox(cmbCountryID, base._presenter.LoadForCMB<CountryENT>(null));
                cmbCountryID.SelectedValueChanged += cmbCountryID_SelectedValueChanged;
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        private void LoadSupplierCarrier()
        {
            try
            {
                _presenter.LoadSupplierCarrier();
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        private DataTable CreateDataTable()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("OrderID", typeof(int));
            dt.Columns.Add("Number", typeof(int));
            dt.Columns.Add("OrderDate", typeof(string));
            dt.Columns["OrderDate"].AllowDBNull = true;
            dt.Columns.Add("OrderNumber", typeof(string));
            dt.Columns["OrderNumber"].AllowDBNull = true;
            dt.Columns.Add("CustomerID", typeof(int));
            dt.Columns["CustomerID"].AllowDBNull = true;
            dt.Columns.Add("CountryID", typeof(int));
            dt.Columns["CountryID"].AllowDBNull = true;
            dt.Columns.Add("Type", typeof(string));
            dt.Columns["Type"].AllowDBNull = true;
            dt.Columns.Add("Weight", typeof(decimal));
            dt.Columns["Weight"].AllowDBNull = true;
            dt.Columns.Add("CustomerCode", typeof(string));
            dt.Columns["CustomerCode"].AllowDBNull = true;
            dt.Columns.Add("CustomerGroupName", typeof(string));
            dt.Columns["CustomerGroupName"].AllowDBNull = true;
            dt.Columns.Add("StandardPrice", typeof(decimal));
            dt.Columns["StandardPrice"].AllowDBNull = true;
            dt.Columns.Add("ListPrice", typeof(decimal));
            dt.Columns["ListPrice"].AllowDBNull = true;

            return dt;
        }

        private DataGridView CreateDataGridView(string key, BindingSource bds)
        {
            DataGridView dtg = new DataGridView();
            dtg.AllowUserToAddRows = false;
            dtg.AllowUserToDeleteRows = false;
            dtg.AllowUserToResizeRows = false;
            Global.SetDoubleBuffered(dtg);

            int index;
            dtg.AutoGenerateColumns = false;
            dtg.Dock = DockStyle.Fill;
            dtg.RowHeadersVisible = false;
            dtg.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dtg.DataSource = bds;

            dtg.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.ColumnHeadersHeight = 42;
            dtg.ReadOnly = true;
            dtg.AllowUserToResizeRows = false;
            dtg.AllowUserToDeleteRows = false;
            dtg.AllowUserToAddRows = false;

            index = dtg.Columns.Add("colOrderID_" + key, "OrderID");
            dtg.Columns[index].Visible = false;
            dtg.Columns[index].DataPropertyName = "OrderID";

            index = dtg.Columns.Add("colNumber_" + key, "#");
            dtg.Columns[index].Width = 40;
            dtg.Columns[index].ReadOnly = true;
            dtg.Columns[index].SortMode = DataGridViewColumnSortMode.NotSortable;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DataPropertyName = "Number";

            index = dtg.Columns.Add("colOrderDate_" + key, "Ngày");
            dtg.Columns[index].DataPropertyName = "OrderDate";
            dtg.Columns[index].DefaultCellStyle.Format = "dd/MM/yyyy";
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            index = dtg.Columns.Add("colOrderNumber_" + key, "Số bill");
            dtg.Columns[index].DataPropertyName = "OrderNumber";
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            index = dtg.Columns.Add("colCustomerName_" + key, "Tên khách hàng");
            dtg.Columns[index].DataPropertyName = "CustomerName";
            dtg.Columns[index].Width = 300;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            index = dtg.Columns.Add("colCustomerPriceListCode_" + key, "Bảng giá bán");
            dtg.Columns[index].DataPropertyName = "CustomerPriceListCode";
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            index = dtg.Columns.Add("colCountryName_" + key, "Đích đến");
            dtg.Columns[index].DataPropertyName = "CountryName";
            dtg.Columns[index].Width = 120;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            index = dtg.Columns.Add("colType_" + key, "Loại");
            dtg.Columns[index].DataPropertyName = "Type";
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].Width = 80;

            index = dtg.Columns.Add("colWeight_" + key, "Trọng lượng (kg)");
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N1";
            dtg.Columns[index].DataPropertyName = "Weight";

            index = dtg.Columns.Add("colCustomerGroupName_" + key, "Nhóm KH");
            dtg.Columns[index].ReadOnly = true;
            dtg.Columns[index].DataPropertyName = "CustomerGroupName";
            dtg.Columns[index].Width = 80;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            index = dtg.Columns.Add("colStandardPrice_" + key, "Giá gốc (USD)");
            dtg.Columns[index].Width = 110;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N2";
            dtg.Columns[index].DataPropertyName = "StandardPrice";
            dtg.Columns[index].Visible = _isViewOriginal;

            index = dtg.Columns.Add("colListPrice_" + key, "Giá bán (USD)");
            dtg.Columns[index].Width = 110;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N2";
            dtg.Columns[index].DataPropertyName = "ListPrice";

            index = dtg.Columns.Add("colVNDListOptional_" + key, "ĐC giá bán tăng (VND)");
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "VNDListOptionalIncrease";

            index = dtg.Columns.Add("colVNDListOptional_" + key, "ĐC giá bán giảm (VND)");
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "VNDListOptionalDecrease";

            index = dtg.Columns.Add("colVNDStandardPrice_" + key, "Giá gốc (VND)");
            dtg.Columns[index].Width = 110;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "VNDStandardPrice";
            dtg.Columns[index].Visible = _isViewOriginal;

            index = dtg.Columns.Add("colVNDListPrice_" + key, "Giá bán (VND)");
            dtg.Columns[index].Width = 110;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "VNDListPrice";

            index = dtg.Columns.Add("colCost_" + key, "Chi phí (VND)");
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "Cost";

            index = dtg.Columns.Add("colDifference_" + key, "Chênh lệch (VND)");
            dtg.Columns[index].Width = 110;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "#,###;(#,###);0";
            dtg.Columns[index].DataPropertyName = "Difference";

            index = dtg.Columns.Add("colRate_" + key, "Tỉ giá");
            dtg.Columns[index].Width = 80;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "Rate";

            index = dtg.Columns.Add("colOriVAT_" + key, "VAT - giá gốc (%)");
            dtg.Columns[index].Width = 80;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "OriVAT";
            dtg.Columns[index].Visible = _isViewOriginal;

            index = dtg.Columns.Add("colVAT_" + key, "VAT - giá bán (%)");
            dtg.Columns[index].Width = 80;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "VAT";

            index = dtg.Columns.Add("colOriFuel_" + key, "Xăng dầu - giá gốc (%)");
            dtg.Columns[index].Width = 90;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N3";
            dtg.Columns[index].DataPropertyName = "OriFuel";

            index = dtg.Columns.Add("colFuel_" + key, "Xăng dầu - giá bán (%)");
            dtg.Columns[index].Width = 90;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N3";
            dtg.Columns[index].DataPropertyName = "Fuel";

            index = dtg.Columns.Add("colDescription_" + key, "Ghi chú");
            dtg.Columns[index].Width = 300;
            dtg.Columns[index].SortMode = DataGridViewColumnSortMode.NotSortable;
            dtg.Columns[index].DataPropertyName = "Description";

            index = dtg.Columns.Add("colTemp_" + key, String.Empty);
            dtg.Columns[index].SortMode = DataGridViewColumnSortMode.NotSortable;
            dtg.Columns[index].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            return dtg;
        }

        private void SetID()
        {
            string[] tmp = tbcOrder.SelectedTab.Name.Split('_');
            if (tmp.Length == 2)
            {
                _supplierID = Utility.IntParse(tmp[0]);
                _carrierID = Utility.IntParse(tmp[1]);
            }
            else
                _supplierID = _carrierID = 0;
        }

        #endregion

        #region Constructors

        public OrderListView()
        {
            InitializeComponent();
            base.ObjectID = (int)Objects.MenuOrder;

            cmbCountryID.DisplayColumns.Add("CountryCode", "Mã nước");
            cmbCountryID.DisplayColumns.Add("CountryName", "Tên tên nước");
            cmbCountryID.DropDownWidth = 300;

            base.Action = ActionName.List;
            base._presenter = _presenter = new OrderListPresenter(this);

            base._lbl.Click += _lbl_Click;
            btnViewAll.Click += btnViewAll_Click;

            btnImportExcel.Visible = _presenter.IsPermission((int)Objects.MenuOrder, (int)Permissions.Import);
            btnExportExcel.Visible = _presenter.IsPermission((int)Objects.MenuOrder, (int)Permissions.Export);
            btnCustomerExport.Visible = _presenter.IsPermission((int)Objects.MenuOrder, (int)Permissions.DebitNote);
            _isViewOriginal = _presenter.IsPermission((int)Objects.MenuOrder, (int)Permissions.ViewOriginal);
        }

        #endregion

        #region Public Properties

        [Search]
        public override string OrderBy
        {
            get { return _orderBy[tbcOrder.SelectedTab.Name]; }
            set { _orderBy[tbcOrder.SelectedTab.Name] = value; }
        }

        [Search]
        public override string OrderDirection
        {
            get { return _orderDirection[tbcOrder.SelectedTab.Name]; }
            set { _orderDirection[tbcOrder.SelectedTab.Name] = value; }
        }

        [Search]
        public int SupplierID
        {
            get { return _supplierID; }
        }

        [Search]
        public int CarrierID
        {
            get { return _carrierID; }
        }

        [Search]
        public DateTime From
        {
            get { return dtpFrom.Value; }
            set
            {
                if (value != DateTime.MinValue)
                    dtpFrom.Value = value;
            }
        }

        [Search]
        public DateTime To
        {
            get { return dtpTo.Value; }
            set
            {
                if (value != DateTime.MinValue)
                    dtpTo.Value = value;
            }
        }

        [Search]
        public string OrderNumber
        {
            get { return txtOrderNumber.Text; }
            set { txtOrderNumber.Text = value; }
        }

        [Search]
        public string Customer
        {
            get { return txtCustomer.Text; }
            set { txtCustomer.Text = value; }
        }

        [Search]
        public decimal FromWeight
        {
            get { return Utility.DecimalParse(txtFromWeight.Text); }
            set
            {
                int numberDigit = Utility.Info.NumberFormat.NumberDecimalDigits;
                try
                {
                    Utility.Info.NumberFormat.NumberDecimalDigits = 1;
                    txtFromWeight.Text = Utility.NumberNParse(value, Utility.Info);
                }
                finally
                {
                    Utility.Info.NumberFormat.NumberDecimalDigits = numberDigit;
                }
            }
        }

        [Search]
        public decimal ToWeight
        {
            get { return Utility.DecimalParse(txtToWeight.Text); }
            set
            {
                int numberDigit = Utility.Info.NumberFormat.NumberDecimalDigits;
                try
                {
                    Utility.Info.NumberFormat.NumberDecimalDigits = 1;
                    txtToWeight.Text = Utility.NumberNParse(value, Utility.Info);
                }
                finally
                {
                    Utility.Info.NumberFormat.NumberDecimalDigits = numberDigit;
                }
            }
        }

        [Search]
        public string Type
        {
            get { return cmbType.Text; }
            set { cmbType.Text = value; }
        }

        [Search]
        public int CountryID
        {
            get { return Utility.IntParse(cmbCountryID.SelectedValue); }
            set { cmbCountryID.SelectedValue = value; }
        }

        public override DataTable Table
        {
            get { return _bindingSource[tbcOrder.SelectedTab.Name].DataSource as DataTable; }
            set
            {
                DataTable dt = value;
                if (!dt.Columns.Contains("Number"))
                {
                    DataColumn column = new DataColumn("Number", typeof(int));
                    column.ReadOnly = false;
                    dt.Columns.Add(column);
                }

                Global.GenerateNumber(ref dt);
                _tables[tbcOrder.SelectedTab.Name] = value;
                _bindingSource[tbcOrder.SelectedTab.Name].DataSource = null;
                _bindingSource[tbcOrder.SelectedTab.Name].DataSource = value;
            }
        }

        public DataTable SupplierCarrier
        {
            set
            {
                DataTable dt;
                BindingSource bds;
                DataGridView dtg;
                TabPage tbp;
                foreach (DataRow row in value.Rows)
                {
                    string key = row["PartnerID"] + "_" + row["CarrierID"];
                    if (!_dataGrids.ContainsKey(key))
                    {
                        dt = CreateDataTable();
                        bds = new BindingSource();
                        bds.DataSource = dt;

                        dtg = CreateDataGridView(key, bds);

                        _tables.Add(key, dt);
                        _dataGrids.Add(key, dtg);
                        _bindingSource.Add(key, bds);
                        _isLoad.Add(key, false);
                        _orderBy.Add(key, "OrderDate");
                        _orderDirection.Add(key, "ASC");

                        tbp = new TabPage(Utility.StringParse(row["PartnerName"]));
                        tbp.Name = key;
                        tbp.Controls.Add(dtg);

                        tbcOrder.TabPages.Add(tbp);
                    }
                }

                dt = CreateDataTable();
                bds = new BindingSource();
                bds.DataSource = dt;

                dtg = CreateDataGridView(String.Empty, bds);

                _tables.Add(String.Empty, dt);
                _dataGrids.Add(String.Empty, dtg);
                _bindingSource.Add(String.Empty, bds);
                _isLoad.Add(String.Empty, false);
                _orderBy.Add(String.Empty, "OrderDate");
                _orderDirection.Add(String.Empty, "ASC");

                tbp = new TabPage("Tổng kết");
                tbp.Name = String.Empty;
                tbp.Controls.Add(dtg);

                tbcOrder.TabPages.Add(tbp);

                tbcOrder_SelectedIndexChanged(tbcOrder, null);
            }
        }

        #endregion

        #region Public Methods

        public override int GetSelected()
        {
            if (_dataGrids[tbcOrder.SelectedTab.Name].CurrentCell == null)
            {
                SetMessage(KZ.Express.Resource.Message.BLM_ERR_SELECT_ITEM.ToString(), false);
                return 0;
            }
            else
                return Utility.IntParse(_dataGrids[tbcOrder.SelectedTab.Name][0, _dataGrids[tbcOrder.SelectedTab.Name].CurrentCell.RowIndex].Value);
        }

        public override void Delete()
        {
            try
            {
                if (Global.ShowMessageConfirm(KZ.Express.Resource.Message.BLM_CFM_DELETE.ToString()) == DialogResult.Yes)
                {
                    string content = Global.GetStringFromDataGridView(_dataGrids[tbcOrder.SelectedTab.Name], 0);
                    _presenter.Delete(content);
                }
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        public void Surcharge()
        {
            SurchargeView view = new SurchargeView();
            view.CarrierID = _carrierID;
            view.ShowDialog();
            btnSearch_Click(btnSearch, null);
        }

        public void Import()
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                int success, unsuccess;
                _errors = _presenter.ImportExcel(ofd.FileName, out success, out unsuccess);
                btnSearch_Click(btnSearch, null);

                base._lbl.Text = "Import thành công: " + success;
                if (unsuccess > 0)
                {
                    base._lbl.Text += ", " + "không thành công: " + unsuccess + ". Click đây để xem chi tiết";
                }

                Cursor = Cursors.Default;
            }
        }

        public void Export()
        {
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();

                Cursor = Cursors.WaitCursor;

                string fileName = sfd.FileName;
                string template = Path.Combine(Application.StartupPath, "Template\\Template.xlt");
                Dictionary<string, string> text = new Dictionary<string, string>();
                int totalCount = 0;
                foreach (TabPage tabpage in tbcOrder.TabPages)
                {
                    string[] tmp = tabpage.Name.Split('_');
                    if (tmp.Length == 2)
                    {
                        _supplierID = Utility.IntParse(tmp[0]);
                        _carrierID = Utility.IntParse(tmp[1]);
                    }
                    else
                        _supplierID = _carrierID = 0;

                    _tables[tabpage.Name] = _presenter.LoadOrder();
                    totalCount += _tables[tabpage.Name].Rows.Count;
                    text.Add(tabpage.Name, tabpage.Text);
                }

                _presenter.ExportExcel(fileName, totalCount, dtpFrom.Value, dtpTo.Value, _tables, text, template);
                SetMessage(KZ.Express.Resource.Message.BLM_SUC_EXPORT.ToString(), true);

                Cursor = Cursors.Default;
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds.ToString());
            }
        }

        public void ExportToCustomer()
        {
            CustomerExportView view = new CustomerExportView();
            view.From = dtpFrom.Value;
            view.To = dtpTo.Value;
            view.ShowDialog();
        }

        public void SelectedTab(int index)
        {
            try
            {
                tbcOrder.SelectedIndexChanged -= tbcOrder_SelectedIndexChanged;
                tbcOrder.SelectedIndex = index;
                SetID();

                btnViewAll_Click(btnViewAll, null);
            }
            finally
            {
                tbcOrder.SelectedIndexChanged += tbcOrder_SelectedIndexChanged;
            }
        }

        #endregion
    }
}
